package com.rhit.rosehack.SQLObjects;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import com.rhit.rosehack.engine.Mob;

import lombok.Data;

public @Data
class Chunk implements SQLObject {
	private int ID;
	private int type;
	private String file;
	private int world_id;
	private ArrayList<Mob> mobList;
	private ArrayList<Item> itemList;
	private char[][] map;
	private int floor;

	public Chunk(int floor, char[][] map, ArrayList<Mob> adder) {
		this();
		this.floor = floor;
		this.map = map;
		this.mobList.addAll(adder);
	}

	public Chunk() {
		this.mobList = new ArrayList<Mob>();
		this.itemList = new ArrayList<Item>();
	}

	public ArrayList<Mob> getMobList() {
		return this.mobList;
	}

	public ArrayList<Item> getItemList() {
		return this.itemList;
	}

	public char[][] getMap() {
		return this.map;
	}

	public void setMap(char[][] setter) {
		this.map = setter;
	}

	public void addMob(Mob toAdd) {
		this.mobList.add(toAdd);
	}

	public void addItem(Item i) {
		this.itemList.add(i);
	}

	public void writeMap(String playerName) throws IOException {
		FileWriter fstream = new FileWriter(playerName + this.ID + ".txt");
		BufferedWriter out = new BufferedWriter(fstream);
		for (char[] k : map) {
			for (char q : k) {
				out.write(q);
			}
			out.write("\n");
		}
		out.close();
	}

	public void retrieveMap(String playerName) throws IOException {
		FileReader fstream = new FileReader(playerName + this.ID + ".txt");
		BufferedReader in = new BufferedReader(fstream);
		int q = 0;
		while (true) {
			String line = in.readLine();
			if (line == null) {
				break;
			}
			map[q] = line.toCharArray();
			q++;
		}
		in.close();
	}

	// Is a monster at X-Y Location
	public boolean monsAt(int x, int y) {
		for (Mob m : mobList) {
			if (m.getX() == x && m.getY() == y)
				return true;
		}

		return false;
	}

	public Item itemAt(int x, int y) {
		for (Item i : itemList) {
			if ((i.getX() == x) && (i.getY() == y))
				return i;
		}

		return null;
	}

	public void removeItem(Item item) {
		itemList.remove(item);
	}
}
